<div class="row">
    <div class="col-lg-12">
        <section class="panel">
            <header class="panel-heading">
                公司客户
            </header>
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-6 col-md-12">
                        <form class="form-inline" role="form" onsubmit="return false;">
                            <div class="form-group">
                                <input type="text" class="form-control" id="Search" placeholder="请输入客户名称/电话号码">
                            </div>
                            <div class="form-group">
                                <input type="text" class="form-control" id="Date" placeholder="创建日期">
                            </div>
                            <div class="form-group">
                                <select id="SearchStaffID" class="form-control">
                                    <option value='0'>请选择负责人</option>
                                    <option value='-1'>公海</option>
                                    <?php
                                    foreach($StaffData as $Key => $Val){
                                        $tID = $Val['ID'];
                                        $tName = $Val['Nick'];
                                        echo "<option value='$tID'>$tName</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <button id="SearchBtn" type="button" class="btn btn-success">搜索</button>
                            <button id="ResetBtn" type="button" class="btn btn-danger">重置</button>
                        </form>
                    </div>
                    <div class="col-lg-6 col-md-12" style="text-align: right">
                        <button id="Add" class="btn btn-danger"><i class=" icon-plus"></i> 新建客户</button>
                        <button id="Import" class="btn"><i class="icon-cloud-upload"></i> 导入</button>
                        <button id="Export" class="btn"><i class="icon-cloud-download"></i> 导出</button>
                    </div>
                </div>
                <div class="row">

                    <div class="col-lg-12">
                        <table id="DataList" lay-filter="DataList" class="table"></table>

                        <script type="text/html" id="HeadToolBar">
                            <div class="layui-btn-container">
<!--                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="toMy"><i-->
<!--                                        class="icon-exchange"></i> 领取-->
<!--                                </button>-->
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="allocation"><i
                                        class="icon-sitemap"></i> 分配
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="changeStatus"><i
                                        class="icon-ok-circle"></i> 更改成交状态
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="export"><i
                                        class="icon-cloud-download"></i> 导出选中
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="delete"><i
                                        class="icon-trash"></i> 删除选中
                                </button>
                            </div>
                        </script>

                        <script type="text/html" id="ToolBar">
<!--                            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="call">拨打</i> </a>-->
<!--                            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</i> </a>-->
<!--                            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</i> </a>-->
                                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="call" title="拨打"><i class="icon-phone"></i> </a>
                                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit" title="编辑"><i class="icon-edit"></i> </a>
                                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="follow" title="跟进"><i class="icon-file-text-alt"></i> </a>
                                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" title="删除"><i class="icon-trash"></i> </a>
                        </script>

                        <!-- 成交状态模板 -->
                        <script type="text/html" id="dealTpl">
                            {{#  if(d.Deal == 0){ }}
                            <i class="icon-remove-circle" style="color: red"></i>未成交
                            {{#  } else { }}
                            <i class="icon-ok-circle" style="color: green"></i>已成交
                            {{#  } }}
                        </script>
                        <!-- 客户级别模板 -->
                        <script type="text/html" id="levelTpl">
                            {{#  var LevelName = GetLevelName(d.Level); }}
                            {{ LevelName }}
                        </script>
                        <!-- 客户来源模板 -->
                        <script type="text/html" id="sourceTpl">
                            {{#  var SourceName = GetSourceName(d.Source); }}
                            {{ SourceName }}
                        </script>
                        <!-- 客户行业模板 -->
                        <script type="text/html" id="industryTpl">
                            {{#  var IndustryName = GetIndustryName(d.Industry); }}
                            {{ IndustryName }}
                        </script>
                    </div>
                </div>


            </div>
        </section>

    </div>
</div>
<!-- 添加客戶提示框 -->
<div id="AddDialog" style="display: none">

    <form class="form-horizontal" role="form">

        <div class="row" style="margin: 15px 15px;">
            <div class="form-group">
                <label class="col-md-3 control-label">客户名称</label>
                <div class="col-md-9">
                    <input id="Name" type="text" class="form-control" placeholder="">
                </div>
            </div>
            <div class="form-group ">
                <label class="col-md-3 control-label">客户级别</label>
                <div class="col-md-9">
                    <select id="Level" class="form-control m-bot15">
                        <option value="A">A类（重点客户）</option>
                        <option value="B">B类（普通客户）</option>
                        <option value="C">C类（非优先客户）</option>
                    </select>
                </div>
            </div>

            <div class="form-group ">
                <label class="col-md-3 control-label">客户行业</label>
                <div class="col-md-9">
                    <select id="Industry" class="form-control m-bot15">
                        <option value="0">请选择</option>
                        <option value="1">IT/通信/电子/互联网</option>
                        <option value="2">金融业</option>
                        <option value="3">房产业</option>
                        <option value="4">商业服务</option>
                        <option value="5">贸易</option>
                        <option value="6">生产</option>
                        <option value="7">运输物品</option>
                        <option value="8">服务业</option>
                        <option value="9">文化传媒</option>
                        <option value="10">政府</option>
                        <option value="11">其他</option>
                    </select>
                </div>
            </div>

            <div class="form-group ">
                <label class="col-md-3 control-label">客户来源</label>
                <div class="col-md-9">
                    <select id="Source" class="form-control m-bot15">
                        <option value="0">请选择</option>
                        <option value="1">促销活动</option>
                        <option value="2">搜索引擎</option>
                        <option value="3">广告</option>
                        <option value="4">转介绍</option>
                        <option value="5">线上注册</option>
                        <option value="6">线上询价</option>
                        <option value="7">预约上门</option>
                        <option value="8">陌拜</option>
                        <option value="9">招商资源</option>
                        <option value="10">公司资源</option>
                        <option value="11">展会资源</option>
                        <option value="12">个人资源</option>
                        <option value="13">电话咨询</option>
                        <option value="14">邮件咨询</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">联系人</label>
                <div class="col-md-9">
                    <input id="Contacts" type="tel" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">电话号码</label>
                <div class="col-md-9">
                    <input id="Phone" type="tel" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">邮箱</label>
                <div class="col-md-9">
                    <input id="Email" type="email" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">地址</label>
                <div class="col-md-9">
                    <input id="Address" type="text" class="form-control" placeholder="">
                </div>
            </div>


            <div class="form-group">
                <label class="col-md-3 control-label">网址</label>
                <div class="col-md-9">
                    <input id="Web" type="text" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">下次联系时间</label>
                <div class="col-md-9">
                    <input id="Next" type="text" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">备注</label>
                <div class="col-md-9">
                    <textarea id="Remark" class="form-control"></textarea>
                </div>
            </div>
        </div>
    </form>

</div>
<!-- 编辑客戶提示框 -->
<div id="EditDialog" style="display: none">

    <form class="form-horizontal" role="form">

        <div class="row" style="margin: 15px 15px;">
            <div class="form-group">
                <label class="col-md-3 control-label">客户名称</label>
                <div class="col-md-9">
                    <input id="Ed_Name" type="text" class="form-control" placeholder="">
                </div>
            </div>
            <div class="form-group ">
                <label class="col-md-3 control-label">客户级别</label>
                <div class="col-md-9">
                    <select id="Ed_Level" class="form-control m-bot15">
                        <option value="A">A类（重点客户）</option>
                        <option value="B">B类（普通客户）</option>
                        <option value="C">C类（非优先客户）</option>
                    </select>
                </div>
            </div>

            <div class="form-group ">
                <label class="col-md-3 control-label">客户行业</label>
                <div class="col-md-9">
                    <select id="Ed_Industry" class="form-control m-bot15">
                        <option value="0">请选择</option>
                        <option value="1">IT/通信/电子/互联网</option>
                        <option value="2">金融业</option>
                        <option value="3">房产业</option>
                        <option value="4">商业服务</option>
                        <option value="5">贸易</option>
                        <option value="6">生产</option>
                        <option value="7">运输物品</option>
                        <option value="8">服务业</option>
                        <option value="9">文化传媒</option>
                        <option value="10">政府</option>
                        <option value="11">其他</option>
                    </select>
                </div>
            </div>

            <div class="form-group ">
                <label class="col-md-3 control-label">客户来源</label>
                <div class="col-md-9">
                    <select id="Ed_Source" class="form-control m-bot15">
                        <option value="0">请选择</option>
                        <option value="1">促销活动</option>
                        <option value="2">搜索引擎</option>
                        <option value="3">广告</option>
                        <option value="4">转介绍</option>
                        <option value="5">线上注册</option>
                        <option value="6">线上询价</option>
                        <option value="7">预约上门</option>
                        <option value="8">陌拜</option>
                        <option value="9">招商资源</option>
                        <option value="10">公司资源</option>
                        <option value="11">展会资源</option>
                        <option value="12">个人资源</option>
                        <option value="13">电话咨询</option>
                        <option value="14">邮件咨询</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">联系人</label>
                <div class="col-md-9">
                    <input id="Ed_Contacts" type="tel" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">电话号码</label>
                <div class="col-md-9">
                    <input id="Ed_Phone" type="tel" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">邮箱</label>
                <div class="col-md-9">
                    <input id="Ed_Email" type="email" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">地址</label>
                <div class="col-md-9">
                    <input id="Ed_Address" type="text" class="form-control" placeholder="">
                </div>
            </div>


            <div class="form-group">
                <label class="col-md-3 control-label">网址</label>
                <div class="col-md-9">
                    <input id="Ed_Web" type="text" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">下次联系时间</label>
                <div class="col-md-9">
                    <input id="Ed_Next" type="text" class="form-control" placeholder="">
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-3 control-label">备注</label>
                <div class="col-md-9">
                    <textarea id="Ed_Remark" class="form-control"></textarea>
                </div>
            </div>


        </div>
    </form>

</div>
<!-- 導入客戶提示框 -->
<div id="ImportDialog" style="display: none">
    <div class="row" style="margin-left: 15px; margin-right: 15px;">
        <div class="col-lg-10 col-lg-offset-1"
             style="padding: 13px 8%;border-radius: 4px;background: #f5f7fa; margin-top: 10px;text-align: center;">
            上传文件 > 导入数据 > 导入完成
        </div>
    </div>
    <div class="row" style="margin-left: 15px; margin-right: 15px;margin-top: 10px;">
        <div class="col-lg-10 col-lg-offset-1">
            <p style="margin: 15px 15px">一、请按照数据模板的格式准备要导入的数据。点击下载 <a href="/uploads/files/客户导入模板.xlsx">《客户导入模板》</a></p>
            <p style="margin: 15px 15px">二、重复时处理处理方式：当前设置唯一字段为：客户名称/手机</p>

            <div>
                <p style="margin: 15px 15px 0px 15px;display: inline">三、电话去重</p>
                <form class="layui-form" action="" style="display: inline">
                    <div class="layui-form-item" style="display: inline">
                        <input id="DistinctPhone" type="checkbox" name="switch" lay-skin="switch" lay-text="ON|OFF">
                    </div>
                </form>
            </div>

            <p style="margin: 15px 15px">四、输入需要过滤客户信息的关键字，用逗号（,）隔开</p>
            <div class="col-lg-12" style="margin: 15px 0px 15px 15px">
                <input id="FilterKeywords" type="text" class="form-control" placeholder="">
            </div>
            <p style="margin: 15px 15px 0px 15px">五、请选择需要导入的文件</p>
            <div class="col-lg-7" style="margin: 15px 0px 15px 15px">
                <input id="OpenFileName" type="text" class="form-control" placeholder="" readonly>
            </div>
            <div class="col-lg-3" style="margin: 15px 0px 15px 15px">
                <button class="btn btn-danger" id="OpenFileBtn">选择文件</button>
                <input type="file" id="OpenFile" style="display: none">
            </div>
        </div>
    </div>

</div>
<!-- 導出客戶提示框 -->
<div id="ExportDialog" style="display: none">
    <h1>Hello world1111</h1>
</div>
<!-- 更改成交状态提示框 -->
<div id="ChangeStatusDialog" style="display: none">

    <section class="panel">
        <div class="panel-body">
            <form class="form-horizontal tasi-form" method="get">
                <div class="form-group">
                    <!--                    <label class="control-label col-lg-2" >Control sizing</label>-->
                    <div class="col-lg-12">
                        <select id="ChangeDeal" class="form-control input-sm m-bot15">
                            <option value="1">已成交</option>
                            <option value="0">未成交</option>
                        </select>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>
<!-- 分配客户给下级 -->
<div id="AllocationDialog" style="display: none">
    <form class="form-horizontal" role="form">
        <div class="row" style="margin: 15px 15px;">

            <div class="form-group ">
                <label class="col-md-3 control-label">员工</label>
                <div class="col-md-9">
                    <select id="StaffID" class="form-control m-bot15">

                        <?php
                            foreach($StaffData as $Key => $Val){
                        $tID = $Val['ID'];
                        $tName = $Val['Nick'];
                        echo "
                        <option value='$tID'>$tName</option>
                        ";
                        }
                        ?>

                    </select>
                </div>
            </div>
        </div>
    </form>
</div>
<!-- 跟进对话框 -->
<div id="FollowDialog" style="display: none">
    <section class="panel">
        <div class="panel-body">
<!--            <div class="row">-->
<!--                <div class="col-lg-10">-->
<!--                    <input id="FollowContent" type="text" class="form-control" placeholder="跟进内容">-->
<!--                </div>-->
<!--                <div class="col-lg-2">-->
<!--                    <button class="btn btn-danger" id="SaveFollowBtn">添加</button>-->
<!--                </div>-->
<!--            </div>-->
            <div>
                <table id="FollowList" lay-filter="FollowList" class="table"></table>
                <script type="text/html" id="FollowToolBar">
                    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" title="删除"><i class="icon-trash"></i> </a>
                </script>
            </div>
        </div>
    </section>

</div>
<script>
    layui.use(['table', 'layer', 'jquery', 'upload', 'laydate'], function () {
        var table = layui.table,
            upload = layui.upload,
            layer = layui.layer,
            laydate = layui.laydate,
            $ = layui.$,
            FollowClientID = 0;

        //跟进记录表
        var followIns = table.render({
            elem: '#FollowList'
            , autoSort: true
            , height: '570'
            , url: '/index.php/user/Client/mb_GetFollowList' //数据接口
            // , page: true //开启分页
            , page: {
                theme: '#ff6c60'
            }
            , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                ClientID: 0
            }
            , limit: 100
            , limits: [100, 200, 300, 400, 500]
            , cols: [[ //表头 總寬度1670
                // {type: 'checkbox', fixed: 'left'}
                {field: 'UserNick', title: '跟进人', width: 100, fixed: 'left'}
                , {field: 'Content', title: '跟进内容', minWidth: 100}
                , {field: 'TimeCreated', title: '跟进时间', width: 160, sort: true}
                // , {title: '編輯', width: 60, align: 'center', toolbar: '#FollowToolBar', fixed: 'right'}
            ]]
        });

        //第一个实例
        var tableIns = table.render({
            elem: '#DataList'
            , autoSort: false   //禁用自動排序
            , height: '690'
            , url: '/index.php/user/Client/mb_CompanyClient' //数据接口
            // , page: true //开启分页
            , toolbar: '#HeadToolBar' //开启头部工具栏，并为其绑定左侧模板
            , page: {
                theme: '#ff6c60'
            }
            , done: function(res, curr, count){
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                console.log(res);
                //得到当前页码
                console.log(curr);
                //得到数据总量
                console.log(count);

                laydate.render({
                    elem: '.xsg-table-dateinput', //指定元素
                    type: 'date',
                    theme: '#ff6c60'
                });
            }
            , limit: 100
            , limits: [100, 200, 300, 400, 500]
            , cols: [[ //表头 總寬度1670
                {type: 'checkbox', fixed: 'left'}
                // , {field: 'ID', title: 'ID', width: 80, sort: true, fixed: 'left'}
                , {field: 'Name', title: '客户名称', width: 200, fixed: 'left'}
                , {field: 'Contacts', title: '联系人', width: 100}
                , {field: 'InCharge', title: '负责人', width: 100}
                // , {field: 'Last', title: '最后跟进时间', width: 160, edit: 'text'}
                // , {field: 'Follow', title: '跟进记录', width: 250, edit: 'text'}
                , {field: 'Deal', title: '成交状态', width: 105, sort: true,templet:'#dealTpl'}
                , {field: 'Level', title: '客户级别', width: 160, sort: true,templet:'#levelTpl'}

                , {field: 'Phone', title: '电话号码', minWidth: 200}
                , {field: 'Email', title: '邮箱', minWidth: 200}
                , {field: 'Address', title: '地址', minWidth: 400}
                , {field: 'Source', title: '客户来源', width: 110, sort: true,templet:'#sourceTpl'}
                , {field: 'Industry', title: '客户行业', width: 200,templet:'#industryTpl'}
                , {field: 'Next', title: '下次联系时间', width: 200, sort: true}
                , {field: 'TimeCreated', title: '创建时间', width: 200, sort: true}
                , {field: 'TimeRegistered', title: '注册日期', width: 125, sort: true}
                , {title: '編輯', width: 168, align: 'center', toolbar: '#ToolBar', fixed: 'right'}
            ]]
        });

        //触发排序事件
        table.on('sort(DataList)', function(obj){ //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            table.reload('DataList', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    Keyword: $('#Search').val(),
                    TimeCreated:$('#Date').val(),
                    OrderField: obj.field, //排序字段
                    OrderType: obj.type //排序方式

                }
            });
        });

        //监听单元格编辑
        table.on('edit(DataList)', function(obj){
            var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段

            var fields = {
                ID: data.ID,
                Field: field,
                Value: value
            };

            global.post('/index.php/user/Client/mb_FollowClient', fields, function (msg) {
                if (msg['code'] == ErrCode_Normal) {
                    layer.msg(msg['msg'], {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    }, function () {

                    });
                    return false;
                } else {
                    mb_OnMessage(msg);
                    return false;
                }
            });
        });

        //监听行工具事件
        table.on('tool(DataList)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if (layEvent === 'call') {
                //打电话
                var fields = {
                    ClientID: data.ID
                };
                global.post('/index.php/user/Client/mb_AddCall', fields, function (msg) {
                    if (msg['code'] == ErrCode_Normal) {
                        layer.msg('添加拨打队列成功', {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {

                        });
                        return false;
                    } else {
                        mb_OnMessage(msg);
                        return false;
                    }
                });
            } else if (layEvent === 'edit') {
                //编辑
                $('#Ed_Name').val(data.Name);
                $('#Ed_Level').val(data.Level);
                $('#Ed_Industry').val(data.Industry);
                $('#Ed_Source').val(data.Source);
                $('#Ed_Contacts').val(data.Contacts);
                $('#Ed_Phone').val(data.Phone);
                $('#Ed_Email').val(data.Email);
                $('#Ed_Address').val(data.Address);
                $('#Ed_Web').val(data.Web);
                $('#Ed_Next').val(data.Next);
                $('#Ed_Remark').val(data.Remark);

                var dialogWidth = '650px';
                if (document.documentElement.scrollWidth < 500) {
                    //手機版
                    dialogWidth = '350px';
                }

                layer.open({
                    type: 1,
                    title: '编辑客户',
                    area: [dialogWidth, '700px'],
                    content: $('#EditDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['保存', '取消'],
                    yes: function (index, layero) {
                        var Name = $('#Ed_Name').val();
                        var Level = $('#Ed_Level').val();
                        var Industry = $('#Ed_Industry').val();
                        var Source = $('#Ed_Source').val();
                        var Contacts = $('#Ed_Contacts').val();
                        var Phone = $('#Ed_Phone').val();
                        var Web = $('#Ed_Web').val();
                        var Next = $('#Ed_Next').val();
                        var Remark = $('#Ed_Remark').val();
                        var Email = $('#Ed_Email').val();
                        var Address = $('#Ed_Address').val();

                        if (Name == '') {
                            layer.msg('请输入客户名称', {icon: 2});
                            return;
                        }
                        if (Phone == '') {
                            layer.msg('请输入电话号码', {icon: 2});
                            return;
                        }

                        var fields = {
                            ClientID: data.ID,
                            Name: Name,
                            Level: Level,
                            Industry: Industry,
                            Source: Source,
                            Contacts: Contacts,
                            Phone: Phone,
                            Web: Web,
                            Next: Next,
                            Remark: Remark,
                            Email: Email,
                            Address: Address,
                        }
                        global.post('/index.php/user/Client/mb_AddEditClient', fields, function (msg) {
                            if (msg['code'] == ErrCode_Normal) {
                                layer.msg('保存成功', {
                                    offset: '15px'
                                    , icon: 1
                                    , time: 1000
                                }, function () {
                                    layer.close(index);
                                    tableIns.reload();
                                });
                                return false;
                            } else {
                                mb_OnMessage(msg);
                                return false;
                            }
                        });
                    },
                    btn2: function (index, layer0) {
                        console.log('取消按下');
                    }
                });
            } else if (layEvent === 'follow'){
                $('#FollowContent').val('');
                var dialogWidth = '650px';
                if (document.documentElement.scrollWidth < 500) {
                    //手機版
                    dialogWidth = '350px';
                }
                FollowClientID = data.ID;
                table.reload('FollowList', {
                    where: {
                        ClientID: data.ID
                    }
                });
                layer.open({
                    type: 1,
                    title: '跟进记录',
                    area: [dialogWidth, '700px'],
                    content: $('#FollowDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                });

            } else if (layEvent === 'del') {
                //删除
                var fields = {
                    Type: 'Client',
                    IDs: data.ID
                };
                global.post('/index.php/user/Event/mb_Delete', fields, function (msg) {
                    if (msg['code'] == ErrCode_Normal) {
                        layer.msg(msg['msg'], {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {
                            tableIns.reload();
                        });
                    } else mb_OnMessage(msg);
                });
            }
        });

        //头工具栏事件
        table.on('toolbar(DataList)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);

            if (checkStatus.data.length == 0) {
                layer.msg('请选择客户', {icon: 2});
                return false
            }

            switch (obj.event) {
                case 'toMy':
                    //领取
                    // var data = checkStatus.data;
                    // layer.alert(JSON.stringify(data));
                    var data = checkStatus.data;
                    var ids = '';
                    for (var i = 0; i < data.length; i++) {
                        ids += data[i].ID;
                        if (i != data.length - 1) ids += ','
                    }
                    var fields = {
                        Type: 'my',
                        IDs: ids
                    };
                    global.post('/index.php/user/Client/mb_ChangeClientOwner', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg(msg['msg'], {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                tableIns.reload();
                            });
                        } else mb_OnMessage(msg);
                    });
                    break;
                case 'allocation':
                    //分配

                    var dialogWidth = '650px';
                    if (document.documentElement.scrollWidth < 500) {
                        //手機版
                        dialogWidth = '350px';
                    }

                    var data = checkStatus.data;
                    var ids = '';
                    for (var i = 0; i < data.length; i++) {
                        ids += data[i].ID;
                        if (i != data.length - 1) ids += ','
                    }

                    var allocationIndex = layer.open({
                        type: 1,
                        title: '分配客户',
                        area: [dialogWidth, '200px'],
                        content: $('#AllocationDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        btn: ['保存', '取消'],
                        yes: function (index, layero) {
                            var fields = {
                                OwnerID: $('#StaffID').val(),
                                Type: 'my',
                                IDs: ids
                            };
                            global.post('/index.php/user/Client/mb_ChangeClientOwner', fields, function (msg) {
                                if (msg['code'] == ErrCode_Normal) {
                                    layer.msg(msg['msg'], {
                                        offset: '15px'
                                        , icon: 1
                                        , time: 1000
                                    }, function () {
                                        layer.close(allocationIndex);
                                        tableIns.reload();
                                    });
                                } else mb_OnMessage(msg);
                            });
                        },
                        btn2: function (index, layer0) {
                            console.log('取消按下');
                        }
                    });
                    break;
                case 'changeStatus':
                    //更改成交狀態

                    var data = checkStatus.data;
                    var ids = '';
                    for (var i = 0; i < data.length; i++) {
                        ids += data[i].ID;
                        if (i != data.length - 1) ids += ','
                    }

                    var dealDialogIndex = layer.open({
                        type: 1,
                        title: '更改成交状态',
                        area: ['350px', '200px'],
                        content: $('#ChangeStatusDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        btn: ['确认', '取消'],
                        yes: function (index, layero) {

                            var fields = {
                                Deal: $('#ChangeDeal').val(),
                                IDs: ids
                            };
                            var loadIndex = layer.load(2, {shade: [0.15, 'rgba(0,0,0,0.50)']});

                            global.post('/index.php/user/Client/mb_ChangeClientDeal', fields, function (msg) {
                                layer.close(loadIndex);
                                if (msg['code'] == ErrCode_Normal) {
                                    layer.msg(msg['msg'], {
                                        offset: '15px'
                                        , icon: 1
                                        , time: 1000
                                    }, function () {
                                        // window.location.reload();
                                        layer.close(dealDialogIndex);
                                        tableIns.reload();
                                    });
                                } else mb_OnMessage(msg);
                            })
                        },
                        btn2: function (index, layero) {
                            console.log('取消按下');
                        }
                    });
                    break;
                case 'export':
                    var data = checkStatus.data;
                    var ids = '';
                    for (var i = 0; i < data.length; i++) {
                        ids += data[i].ID;
                        if (i != data.length - 1) ids += ','
                    }
                    var fields = {
                        Type: 'company',
                        IDs: ids
                    };
                    var loadIndex = layer.load(2, {shade: [0.15, 'rgba(0,0,0,0.50)']});
                    global.post('/index.php/user/Client/mb_ExportClient', fields, function (msg) {
                        layer.close(loadIndex);
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg(msg['msg'], {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                // window.location.reload();
                                window.open(msg['data']['url']);
                            });
                        } else mb_OnMessage(msg);
                    })
                    break;
                case 'delete':
                    //刪除選中
                    var data = checkStatus.data;
                    var ids = '';
                    for (var i = 0; i < data.length; i++) {
                        ids += data[i].ID;
                        if (i != data.length - 1) ids += ','
                    }
                    var fields = {
                        Type: 'Client',
                        IDs: ids
                    };
                    global.post('/index.php/user/Event/mb_Delete', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg(msg['msg'], {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                // window.location.reload();
                                tableIns.reload();
                            });
                        } else mb_OnMessage(msg);
                    });
                    break;
                default:
                    break;
            }
        });

        //新增客戶
        $('#Add').bind('click', function () {
            var dialogWidth = '650px';
            if (document.documentElement.scrollWidth < 500) {
                //手機版
                dialogWidth = '350px';
            }

            layer.open({
                type: 1,
                title: '新增客户',
                area: [dialogWidth, '700px'],
                content: $('#AddDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['保存', '取消'],
                yes: function (index, layero) {
                    var Name = $('#Name').val();
                    var Level = $('#Level').val();
                    var Industry = $('#Industry').val();
                    var Source = $('#Source').val();
                    var Contacts = $('#Contacts').val();
                    var Phone = $('#Phone').val();
                    var Web = $('#Web').val();
                    var Next = $('#Next').val();
                    var Remark = $('#Remark').val();
                    var Email = $('#Email').val();
                    var Address = $('#Address').val();

                    if (Name == '') {
                        layer.msg('请输入客户名称', {icon: 2});
                        return;
                    }
                    if (Phone == '') {
                        layer.msg('请输入电话号码', {icon: 2});
                        return;
                    }

                    var fields = {
                        Type: 'pub',
                        Name: Name,
                        Level: Level,
                        Industry: Industry,
                        Source: Source,
                        Contacts: Contacts,
                        Phone: Phone,
                        Web: Web,
                        Next: Next,
                        Remark: Remark,
                        Email: Email,
                        Address: Address,
                    }
                    global.post('/index.php/user/Client/mb_AddEditClient', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg('保存成功', {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                layer.close(index);
                                tableIns.reload()
                            });
                            return false;
                        } else {
                            mb_OnMessage(msg);
                            return false;
                        }
                    });
                },
                btn2: function (index, layer0) {
                    console.log('取消按下');
                }
            });
            // console.log(document.documentElement.scrollWidth);
        });

        //导入客户
        $('#Import').bind('click', function () {

            var dialogWidth = '700px';
            if (document.documentElement.scrollWidth < 500) {
                //手機版
                dialogWidth = '350px';
            }

            layer.open({
                type: 1,
                title: '导入',
                area: [dialogWidth, '480px'],
                content: $('#ImportDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['确认导入', '取消'],
                yes: function (index, layero) {

                    var obj = document.getElementById('OpenFile').files;
                    var abn = obj[0].name;
                    var lastname = abn.substring(abn.lastIndexOf(".")).toLowerCase();
                    if (!(lastname == ".xls" || lastname == ".xlsx")) {
                        layer.msg('请选择Excel文件');
                        return;
                    }

                    var formData = new FormData();
                    formData.append('ExcelFile', obj[0]);
                    formData.append('Type', 'pub');
                    formData.append('DistinctPhone', $('#DistinctPhone').val());
                    formData.append('Filter', $('#FilterKeywords').val());
                    var loadIndex = layer.load(2, {shade: [0.15, 'rgba(0,0,0,0.50)']});

                    $.ajax({
                        type: "POST",
                        url: "/index.php/user/Client/mb_ImportClient",  //上傳接口
                        dataType: "json",
                        data: formData,
                        // 不处理发送的数据
                        processData: false,
                        // 不设置Content-Type请求头
                        contentType: false,
                        async: true,
                        success: function (msg) {
                            //上传

                            if (msg['code'] == ErrCode_Normal) {
                                global.log('收到数据', msg);
                                var Data = msg['data'];
                                var Content = '共导入成功' + Data['SuccessCount'] + '条记录<br>共跳过' + Data['FilterCount'] + '条记录<br><hr>共导入失败' + Data['FailureCount'] + '条记录：<br>';
                                for (var i = 0; i < Data['Failure'].length; i++) {
                                    var tMsg = Data['Failure'][i]['Msg'];
                                    Content += tMsg + '<br>';
                                }

                                layer.open({
                                    title: '导入结果'
                                    , content: Content
                                    , yes: function (tIndex, tLayero) {
                                        window.location.reload();
                                    }
                                });
                                return false;
                            } else mb_OnMessage(msg);
                        },
                        complete: function () {
                            layer.close(loadIndex);
                        }
                    });
                },
                btn2: function (index, layero) {
                    console.log('取消按下');
                }
            });
            // console.log(document.documentElement.scrollWidth);
        });
        //导出客户
        $('#Export').bind('click', function () {
            var loadIndex = layer.load(2, {shade: [0.15, 'rgba(0,0,0,0.50)']});
            var fields = {
                Type: 'company',
                IDs: ''
            };
            global.post('/index.php/user/Client/mb_ExportClient', fields, function (msg) {
                layer.close(loadIndex);
                if (msg['code'] == ErrCode_Normal) {
                    layer.msg(msg['msg'], {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    }, function () {
                        // window.location.reload();
                        window.open(msg['data']['url']);
                    });
                } else mb_OnMessage(msg);
            });
        });

        $('#OpenFileBtn').bind('click', function () {
            $('#OpenFile').click();
        });

        $("#OpenFile").change(function () {
            var obj = this.files;
            var abn = obj[0].name;
            var lastname = abn.substring(abn.lastIndexOf(".")).toLowerCase();
            if (!(lastname == ".xls" || lastname == ".xlsx")) {
                layer.msg('请选择Excel文件');
                return;
            }
            $('#OpenFileName').val(abn);
        })

        laydate.render({
            elem: '#Next', //指定元素
            type: 'datetime',
            theme: '#ff6c60'
        });
        laydate.render({
            elem: '#Date', //指定元素
            type: 'date',
            theme: '#ff6c60'
        });
        //搜寻按钮按下
        $('#SearchBtn').bind('click', function () {
            var Keyword = $('#Search').val();
            var Date = $('#Date').val();
            var StaffID = $('#SearchStaffID').val();
            // if (Keyword == '' && Date == '' ) {
            //     layer.msg('请输入客户名称/电话号码或创建日期', {icon: 2});
            //     return false;
            // }
            table.reload('DataList', {
                where: {
                    Keyword: Keyword,
                    Date: Date,
                    StaffID: StaffID
                }
            });
        });
        $('#Search').bind('keypress', function (event) {
            if (event.keyCode == "13") {
                //需要处理的事情
                var Keyword = $('#Search').val();
                if (Keyword == '') {
                    layer.msg('请输入客户名称/电话号码', {icon: 2});
                    return false;
                }
                table.reload('DataList', {
                    where: {
                        Keyword: Keyword
                    }
                });
            }
        });
        $('#ResetBtn').bind('click', function () {
            $('#Search').val('');
            $('#Date').val('');
            $('#SearchStaffID').val('');
            table.reload('DataList', {
                where: {
                    Keyword: '',
                    Date: '',
                    StaffID: 0,
                }
            });
        });
    });

    function mb_GetFileUrl(file) {
        var url = ''
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(flie);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(flie);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(flie);
        }
        return url;
    }

</script>
<style>
    .layui-table-tips-c:before {
        position: relative;
        right: 1px;
        bottom: 3.5px;
    }
    .layui-form-switch{
        margin-top: -1px;
    }
</style>